package com.xuecheng.content.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xuecheng.base.exception.ValidatedGroups;
import com.xuecheng.content.exception.CourseFailedSaveTeacherException;
import com.xuecheng.content.exception.CourseTeacherNotExistException;
import com.xuecheng.content.mapper.CourseTeacherMapper;
import com.xuecheng.content.model.dto.SaveOrUpdateCourseTeacherDTO;
import com.xuecheng.content.model.po.CourseTeacher;
import com.xuecheng.content.service.ICourseTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程-教师关系表 服务实现类
 * </p>
 *
 * @author 勾新杰
 * @since 2025-01-09
 */
@Service
@RequiredArgsConstructor
public class CourseTeacherServiceImpl extends ServiceImpl<CourseTeacherMapper, CourseTeacher> implements ICourseTeacherService {

    private final CourseTeacherMapper courseTeacherMapper;

    /**
     * 根据课程id查询教师信息
     *
     * @param courseId 课程id
     * @return 教师信息
     */
    @Override
    public List<CourseTeacher> list(Long courseId) {
        return courseTeacherMapper.list(courseId);
    }

    /**
     * 添加教师信息
     *
     * @param saveCourseTeacherDTO 课程教师信息
     * @return 添加结果
     */
    @Override
    public CourseTeacher save(SaveOrUpdateCourseTeacherDTO saveCourseTeacherDTO) {
        // 1. 封装课程教师信息
        CourseTeacher courseTeacher = BeanUtil.copyProperties(saveCourseTeacherDTO, CourseTeacher.class);
        courseTeacher.setCreateDate(LocalDateTime.now());
        // 2. 添加课程教师信息
        int insert = courseTeacherMapper.insert(courseTeacher);
        if (insert <= 0) CourseFailedSaveTeacherException.cast();
        // 3. 返回课程教师信息，id由mp帮我们填充
        return courseTeacher;
    }

    /**
     * 修改课程教师信息
     *
     * @param updateCourseTeacherDTO 修改课程教师信息
     * @return 返回修改后的结果
     */
    @Override
    public CourseTeacher update(SaveOrUpdateCourseTeacherDTO updateCourseTeacherDTO) {
        CourseTeacher courseTeacher = BeanUtil.copyProperties(updateCourseTeacherDTO, CourseTeacher.class);
        courseTeacherMapper.updateById(courseTeacher);
        return courseTeacherMapper.selectById(courseTeacher.getId());
    }

    /**
     * 删除课程教师信息
     *
     * @param courseId 课程id
     * @param id       教师id
     */
    @Override
    public void remove(Long courseId, Long id) {
        CourseTeacher courseTeacher = lambdaQuery()
                .eq(CourseTeacher::getCourseId, courseId)
                .eq(CourseTeacher::getId, id)
                .one();
        if (courseTeacher == null) CourseTeacherNotExistException.cast();
        courseTeacherMapper.deleteById(courseTeacher);
    }
}
